package com.saihai.jiankang;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.itextpdf.text.*;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import com.saihai.common.utils.StringUtils;
import com.saihai.jiankang.student.domain.UfXs;
import com.saihai.jiankang.student.service.IUfXsService;
import com.saihai.jiankang.zzjg.domain.UfZzjg;
import com.saihai.jiankang.zzjg.service.IUfZzjgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.awt.Font;
import java.io.*;
import java.util.*;

import javax.imageio.ImageIO;
import javax.xml.crypto.Data;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@RestController
@RequestMapping("/jiankang/testpdf")
public class testPDF {

    @Autowired
    private IUfZzjgService ufZzjgService;

    @Autowired
    private IUfXsService ufXsService;

    public static void generateQRCodeWithDescription(String content, String name, String id, String school, int width, int height, String outputFilePath)
            throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height);

        BufferedImage qrImage = MatrixToImageWriter.toBufferedImage(bitMatrix);

        Graphics2D g2d = qrImage.createGraphics();
        g2d.setColor(Color.BLACK);
        Font font = new Font("宋体", Font.PLAIN, 12);
        g2d.setFont(font);

        // 绘制姓名
        g2d.drawString("姓名：" + name, 10, 15);

        // 绘制学校
        g2d.drawString("班级：" + school, 10, 30);

        // 绘制身份证号
        g2d.drawString("身份证：" + id, 10, height - 10);

        g2d.dispose();

        ImageIO.write(qrImage, "png", new File(outputFilePath));
    }

    public static void generatePDFWithQRCodes(List<String> contents, List<String> names, List<String> ids, List<String> schools, String outputPdfPath) throws DocumentException, IOException {
        Document document = new Document(PageSize.A4);
        PdfWriter.getInstance(document, new FileOutputStream(outputPdfPath));

        document.open();
        PdfPTable table = new PdfPTable(2); // 设置为两列，实现横向排版

        for (int i = 0; i < contents.size(); i++) {
            String qrCodeFilePath = "qr_code_" + i + ".png";
            try {
                generateQRCodeWithDescription(contents.get(i), names.get(i), ids.get(i), schools.get(i), 300, 300, qrCodeFilePath);
            } catch (WriterException e) {
                e.printStackTrace();
            }

            Image qrImage = Image.getInstance(qrCodeFilePath);
            table.addCell(qrImage);
            if ((i + 1) % 2 == 0 || i == contents.size() - 1) {
                table.addCell(new Phrase(""));
                table.completeRow();
            }
        }

        document.add(table);

        document.close();
    }

    public static void compressPdfToZip(String pdfFilePath, String zipFilePath) throws IOException {
        File pdfFile = new File(pdfFilePath);
        File zipFile = new File(zipFilePath);

        try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile))) {
            ZipEntry entry = new ZipEntry(pdfFile.getName());
            zipOut.putNextEntry(entry);

            try (FileInputStream fis = new FileInputStream(pdfFile)) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = fis.read(buffer)) > 0) {
                    zipOut.write(buffer, 0, len);
                }
            }

            zipOut.closeEntry();
        }
    }

    public static void compressPdfsToZip(List<String> pdfFilePaths, String zipFilePath) throws IOException {
        File zipFile = new File(zipFilePath);

        try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile))) {
            for (String pdfFilePath : pdfFilePaths) {
                File pdfFile = new File(pdfFilePath);
                ZipEntry entry = new ZipEntry(pdfFile.getName());
                zipOut.putNextEntry(entry);

                try (FileInputStream fis = new FileInputStream(pdfFile)) {
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = fis.read(buffer)) > 0) {
                        zipOut.write(buffer, 0, len);
                    }
                }

                zipOut.closeEntry();
            }
        }
    }


    @PostMapping("/download-zip")
    public ResponseEntity<byte[]> downloadZip(UfXs ufXs) throws IOException {
        List<String> pdfFilePaths = new ArrayList<>();
        UfZzjg ufZzjg = new UfZzjg();
        if (StringUtils.isNotNull(ufXs.getSzbjId())) {
            ufZzjg.setId(Long.parseLong(ufXs.getSzbjId()));
        }
        ufZzjg.setLx(6L);
        List<UfZzjg> list = ufZzjgService.selectChildDept(ufZzjg);

        for (int i = 0; i < list.size(); i++) {

            UfXs ufXs1 = new UfXs();
            ufXs1.setSzbjId(list.get(i).getId().toString());
            List<UfXs> list_xs = ufXsService.selectUfXsList(ufXs1);
            List<String> contents = new ArrayList<>();
            List<String> names = new ArrayList<>();
            List<String> ids = new ArrayList<>();
            List<String> schools = new ArrayList<>();
            if (list_xs.size() > 0) {
                for (int j = 0; j < list_xs.size(); j++) {
                    contents.add(list_xs.get(j).getId().toString());
                    names.add(list_xs.get(j).getXm());
                    ids.add(list_xs.get(j).getZjhm());
                    schools.add(list_xs.get(j).getBj());
                }

            }
            String pdfFilePath = "D:/" + list.get(i).getMc() + "_" + i + ".pdf";
            try {
                generatePDFWithQRCodes(contents, names, ids, schools, pdfFilePath);
                pdfFilePaths.add(pdfFilePath);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        String uuid2 = UUID.randomUUID().toString();
        String zipFilePath = "D:/qr_codes" + uuid2 + ".zip";
        try {
            compressPdfsToZip(pdfFilePaths, zipFilePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 压缩 PDF 文件到 ZIP
        compressPdfsToZip(pdfFilePaths, zipFilePath);

        File zipFile = new File(zipFilePath);
        try (FileInputStream fis = new FileInputStream(zipFile);
             ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) > 0) {
                baos.write(buffer, 0, len);
            }
            byte[] content = baos.toByteArray();

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", zipFile.getName());
            for (int i=0 ;i<pdfFilePaths.size();i++) {
                File file = new File(pdfFilePaths.get(i));
                if (file.exists()) {
                    file.delete();
                }
            }

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(content);
        }
    }

//    public static void main(String[] args) {
//        List<String> contents = new ArrayList<>();
//        List<String> names = new ArrayList<>();
//        List<String> ids = new ArrayList<>();
//        List<String> schools = new ArrayList<>();
//
//        contents.add("https://example.com/qr1");
//        names.add("张三");
//        ids.add("500000000000000");
//        schools.add("学校");
//
//        contents.add("https://example.com/qr2");
//        names.add("姓名 2");
//        ids.add("ID 2");
//        schools.add("学校 2");
//
//        try {
//            generatePDFWithQRCodes(contents, names, ids, schools, "D:/qr_codes.pdf");
//            System.out.println("PDF generated successfully.");
//        } catch (DocumentException | IOException e) {
//            e.printStackTrace();
//        }
//    }

//    @GetMapping("/abc")
//    public ResponseEntity<byte[]> generateQRCodePDFAndZip1() throws IOException {
//        List<String> contents = new ArrayList<>();
//        List<String> names = new ArrayList<>();
//        List<String> ids = new ArrayList<>();
//        List<String> schools = new ArrayList<>();
//
//        contents.add("https://example.com/qr1");
//        names.add("姓名 1");
//        ids.add("ID 1");
//        schools.add("学校 1");
//
//        contents.add("https://example.com/qr2");
//        names.add("姓名 2");
//        ids.add("ID 2");
//        schools.add("学校 2");
//
//        String pdfFilePath = "D:/qr_codes123.pdf";
//        try {
//            generatePDFWithQRCodes(contents, names, ids, schools, pdfFilePath);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        // 创建临时压缩文件
//        File tempZipFile = File.createTempFile("qr_codes", ".zip");
//        try (ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(new FileOutputStream(tempZipFile))) {
//            ZipArchiveEntry entry = new ZipArchiveEntry(tempZipFile.getName());
//            zipOut.putArchiveEntry(entry);
//            // 将 PDF 文件添加到压缩文件中
//            try (InputStream inputStream = new FileSystemResource(pdfFilePath).getInputStream();
//                 ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
//                byte[] buffer = new byte[1024];
//                int len;
//                while ((len = inputStream.read(buffer)) > 0) {
//                    baos.write(buffer, 0, len);
//                }
//                zipOut.write(baos.toByteArray());
//            }
//            zipOut.closeArchiveEntry();
//        }
//
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//        headers.setContentDispositionFormData("attachment", "qr_codes.zip");
//
//        try (InputStream inputStream = new FileSystemResource(tempZipFile).getInputStream();
//             ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
//            byte[] buffer = new byte[1024];
//            int len;
//            while ((len = inputStream.read(buffer)) > 0) {
//                baos.write(buffer, 0, len);
//            }
//            return ResponseEntity.ok()
//                    .headers(headers)
//                    .body(baos.toByteArray());
//        }
//    }

}